﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using Bussiness;
using Model;
using AssureMessage = Bussiness.AssureMessage;
using Depot = Model.Depot;
using Product = Model.Product;
using Store = Model.ProductStore;
using Employ = Model.Employ;
using DropProduct = Model.DropProduct;
using Branch = Model.Branch;
using Client = Model.Client;
using OrderDetail = Model.OrderDetail;
using Sale = Model.Sale;
using SaleDetail = Model.SaleDetail;
using ExtensionDataObject= System.Runtime.Serialization.ExtensionDataObject;
using System.Xml.Serialization;
namespace Services1
{
    /// <summary>
    /// Summary description for WebService1
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
        // [System.Web.Script.Services.ScriptService]
    public class WebService1 : System.Web.Services.WebService
    {

        //cambiar la direccion por la direccion de cada servidor

        private Dictionary<string, string> AdressIp = new Dictionary<string, string> { 
        { "Quillacollo", "http://192.168.0.10/Quillacollo/WebService.asmx" }, 
        { "Colcapirhua", "http://192.168.0.10/Colcapirhua/WebService.asmx" }, 
        { "Cercado", "http://192.168.0.11/Cercado/WebService.asmx" }, 
        { "Oquendo", "http://192.168.0.11/Oquendo/WebService.asmx" }, 
        //{ "Javier", "http://192.168.1.8/WebService.asmx" } ,
        //{"Javier1", "http://192.168.1.8:81/WebService.asmx"}
        };
        private string BranchId=System.Configuration.ConfigurationSettings.AppSettings["BranchName"];

        #region Product Services

        [WebMethod]
        public string HelloWorld()
        {
            return "Hello World";
        }

        [WebMethod]
        public AssureMessage RegisterProduct(Product product, Model.ProductStore store)
        {
            return ProductManager.RegisterProduct(product, store);
        }

        [WebMethod]
        public List<Product> GetProductList()
        {
            return ProductManager.GetProductList().ToList();
        }

        #endregion

        #region Store Services

        [WebMethod]
        public AssureMessage RegisterStore(Store store)
        {
            return StoreManager.RegisterStore(store);

        }

        [WebMethod]
        public AssureMessage ModifyStore(Store store)
        {
            return StoreManager.ModifyStore(store);
        }

        [WebMethod]
        public List<Store> GetListStore()
        {
            return StoreManager.GetListStore().ToList();
        }

        #endregion

        #region Depot Services

        [WebMethod]
        public AssureMessage RegisterDepot(Depot depot)
        {

            return DepotManager.RegisterDepot(depot);

        }

        [WebMethod]
        public AssureMessage ModifyDepot(Depot depot)
        {
            return DepotManager.ModifyDepot(depot);
        }

        [WebMethod]
        public List<Depot> GetListDepot()
        {
            return DepotManager.GetListDepot().ToList();
        }

        #endregion


        //[WebMethod]
        //public string gets()
        //{
        //    ServiceReference1.WebService1SoapClient c = 
        //new WebService1SoapClient("WebService1Soap", "http://192.168.1.12/CamperoSSDD/WebService.asmx");
        //    return c.Saludo();
        //}



        [WebMethod]
        public Client GetClientByCi(string clientId)
        {

            return SearchClientInAllBranch(clientId);
        }

        [WebMethod]
        public void RegisterClient(Client newClient)
        {

            var c = new Service.Client
                        {
                            ClientId = newClient.ClientId,
                            ClientAddress = newClient.ClientAddress,
                            ClientName = newClient.ClientName,
                            ClientPhone = newClient.ClientPhone
                        };

            foreach (KeyValuePair<string, string> keyValuePair in AdressIp)
            {
                var client = new Service.WebService1SoapClient("WebService1Soap", keyValuePair.Value);
                client.RegisterClientInBranch(c);
            }
        }

        [WebMethod]
        public void RegisterClientInBranch(Client newClient)
        {
            ManagerClient.RegisterOrUpdateClient(newClient);
        }
        private Client SearchClientInAllBranch(string clientId)
        {
            var findClient = new Service.Client { ClientId = clientId };

            foreach (KeyValuePair<string, string> keyValuePair in AdressIp)
            {
                var client = new Service.WebService1SoapClient("WebService1Soap", keyValuePair.Value);
                var c = client.SearchClientInBranch(findClient);
                if (c != null)
                {
                    return new Client
                               {
                                   ClientId = c.ClientId,
                                   ClientAddress = c.ClientAddress,
                                   ClientName = c.ClientName,
                                   ClientPhone = c.ClientPhone
                               };
                }
            }
            return new Client { ClientId = clientId, ClientAddress = "", ClientName = "", ClientPhone = "" };
        }

        [WebMethod]
        public Client SearchClientInBranch(Client clientFind)
        {
            return ManagerClient.FindClient(clientFind);
        }


        [WebMethod]
        public List<DropProduct> ProductAvailability(string productId)
        {
            var prods = new List<DropProduct>();
            foreach (KeyValuePair<string, string> keyValuePair in AdressIp)
            {
                var client = new Service.WebService1SoapClient("WebService1Soap", keyValuePair.Value);
                var c = client.ProductAvailabilityInBranch(productId);
                if(c!=null)
                if (c.ProductQuantity != 0)
                {
                    var c1 = new DropProduct() { 
                        ProductPrice = c.ProductPrice,
                        BranchId = keyValuePair.Key, 
                        ProductId = productId, 
                        ProductQuantity = c.ProductQuantity, 
                        BranchName = keyValuePair.Key,
                        ProductName = ProductManager.GetProductById(productId).Name};
                    prods.Add(c1);
                }
            }
            return prods;
        }

        [WebMethod]
        public ProductStore GetProductStoreById(string productId)
        {
            return Bussiness.ProductManager.GetProductStoreById(productId);
        }

        [WebMethod]
        public DropProduct ProductAvailabilityInBranch(string productId)
        {
            var q = ProductManager.GetProductStoreById(productId);
            if (q != null)
            {
                var p = new DropProduct {ProductQuantity = 0, ProductId = productId, ProductPrice = q.StorePriceByUnit};
                p.ProductQuantity += ProductManager.GetProductAvailabilityInStore(productId);
                //p.ProductQuantity += ProductManager.GetProductAvailabilityInStock(productId);
                return p;
            }
            return null;
        }

        [WebMethod]
        public void MakeSale(List<SaleDetail> saleDetail, Sale dataSale, List<DropProduct> productDrop)
        {
            List<Order> orders = ProductManager.GetOrdersFromProduct(productDrop, BranchId);
            SendOrdersForEachBranch(orders);
            dataSale.SaleDetails = saleDetail;
            ProductManager.SaveSale(dataSale);
        }

        private void SendOrdersForEachBranch(IEnumerable<Order> orders)
        {
            foreach (var order in orders)
            {
                var client = new Service.WebService1SoapClient("WebService1Soap", AdressIp[order.BranchLocalId]);
                client.MakeReserve(getOrderServiceFromOrder(order));
            }
        }

        private Service.Order getOrderServiceFromOrder(Order order)
        {
            var o = new Service.Order() { BranchLocalId = order.BranchLocalId, BranchRemoteId = order.BranchRemoteId, OrderDetails = new Service.OrderDetail[order.OrderDetails.Count] };
            for (int i = 0; i < order.OrderDetails.Count; i++)
            {
                o.OrderDetails[i] = new Service.OrderDetail()
                {
                    ProductId = order.OrderDetails.ElementAt(i).ProductId,
                    Quantity = order.OrderDetails.ElementAt(i).Quantity
                };
            }
            return o;
        }

        [WebMethod]
        public void MakeReserve(Order o)
        {
            ProductManager.SaveReserve(o);
        }

        [WebMethod]
        public bool Login(Employ user)
        {
            return ManagerEmploy.EmployUserExist(user);
        }

        [WebMethod]
        public List<Employ> ListEmploy()
        {
            return ManagerEmploy.GetAllEmploy;
        }

        [WebMethod]
        public void RegisterEmploy(Employ newEmploy)
        {
             ManagerEmploy.RegisterOrUpdateEmployee(newEmploy);
        }

        [WebMethod]
        public List<Model.OrderDetail> GetOrderDetailBySaleId(string branchId)
        {
            var q = ManagerOrder.GetOrderDetailForBranch(branchId);
            return q.ToList();
        }

        [WebMethod]
        public void ConfirmationOrder(string branchId)
        {
            ProductManager.RegisterCheckOutProduct(branchId);
        }

        [WebMethod]
        public List<string> GetBranchesHaveOrderPending()
        {
            return ProductManager.GetAllBranchWithOrders();
        }
    }
}
